package org.jeecg.modules.mes.produce.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.math.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.mes.chiefdata.entity.MesChiefdataBomitem;
import org.jeecg.modules.mes.chiefdata.entity.MesChiefdataMateriel;
import org.jeecg.modules.mes.chiefdata.entity.MesChiefdataReplacematerial;
import org.jeecg.modules.mes.chiefdata.entity.MesPrintModel;
import org.jeecg.modules.mes.client.StockClient;
import org.jeecg.modules.mes.client.SystemClient;
import org.jeecg.modules.mes.client.TransactionClient;
import org.jeecg.modules.mes.order.entity.MesOrderProduce;
import org.jeecg.modules.mes.order.entity.MesProduceItem;
import org.jeecg.modules.mes.print.conHead;
import org.jeecg.modules.mes.print.conmap;
import org.jeecg.modules.mes.print.mesUtil;
import org.jeecg.modules.mes.produce.entity.MesCommandbillInfo;
import org.jeecg.modules.mes.produce.entity.MesCommandbillPitem;
import org.jeecg.modules.mes.produce.entity.MesOnlineMaterieltable;
import org.jeecg.modules.mes.produce.entity.MesWorkbillInfo;
import org.jeecg.modules.mes.produce.service.*;
import org.jeecg.modules.mes.storage.entity.MesStorageWholesale;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;

/**
 * @Description: 制造中心-制令单信息
 * @Author: jeecg-boot
 * @Date: 2020-10-13
 * @Version: V1.0
 */
@Api(tags = "制造中心-制令单信息")
@RestController
@RequestMapping("/produce/mesCommandbillInfo")
@Slf4j
public class MesCommandbillInfoController extends JeecgController<MesCommandbillInfo, IMesCommandbillInfoService> {
    @Autowired
    private IMesCommandbillInfoService mesCommandbillInfoService;
    @Autowired
    private IMesCommandbillPitemService mesCommandbillPitemService;
    @Autowired
    private IMesWorkbillInfoService mesWorkbillInfoService;
    @Autowired
    private IMesOnlineMaterieltableService mesOnlineMaterieltableService;
    @Autowired
    private SystemClient systemClient;
    @Autowired
    private TransactionClient transactionClient;
    @Autowired
    StockClient stockClient;
    @Autowired
    private IMesOnlineMaterieltableMainService mesOnlineMaterieltableMainService;

    private ExecutorService executor = Executors.newCachedThreadPool();

    /*---------------------------------主表处理-begin-------------------------------------*/

    /**
     * 分页列表查询
     *
     * @param mesCommandbillInfo
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "制造中心-制令单信息-分页列表查询")
    @ApiOperation(value = "制造中心-制令单信息-分页列表查询", notes = "制造中心-制令单信息-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(MesCommandbillInfo mesCommandbillInfo,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        //修改领料清单的未发料库存为0
        QueryWrapper<MesCommandbillInfo> queryWrapper = QueryGenerator.initQueryWrapper(mesCommandbillInfo, req.getParameterMap());
        queryWrapper.orderByDesc("create_time");
        Page<MesCommandbillInfo> page = new Page<MesCommandbillInfo>(pageNo, pageSize);
        IPage<MesCommandbillInfo> pageList = mesCommandbillInfoService.page(page, queryWrapper);
        for (MesCommandbillInfo info : pageList.getRecords()) {
            if (StringUtils.isNotBlank(info.getMechanismCode())) {
                MesChiefdataMateriel chiefDataMateriel = systemClient.queryByProductCode(info.getMechanismCode());//根据机种料号获取客户料号
                if (com.epms.util.ObjectHelper.isNotEmpty(chiefDataMateriel) && StringUtils.isNotBlank(chiefDataMateriel.getQuery2())) {
                    info.setClientCode(chiefDataMateriel.getQuery2());
                }
            }
        }
        return Result.ok(pageList);
    }

    @AutoLog(value = "制造中心-结束抽检")
    @ApiOperation(value = "制造中心-结束抽检", notes = "制造中心-结束抽检")
    @GetMapping(value = "/commitCheck")
    public Result<?> commitCheck(@RequestParam(name = "id", required = true) String id) {
        MesCommandbillInfo mesCommandbillInfo = mesCommandbillInfoService.getById(id);
        if (mesCommandbillInfo == null) {
            return Result.error("未找到对应数据");
        }
        mesCommandbillInfo.setCheckState("已完成");
        mesCommandbillInfoService.updateById(mesCommandbillInfo);
        return Result.ok("结束成功");
    }

    /**
     * app，显示制令单发料、上料、退料、转产的详情页信息
     *
     * @param mesCommandbillInfo
     * @param oldCode            原有制令单号
     * @param newCode            转产制令单号
     * @param choice             转产/退料
     * @param planNum            制令单计划数量
     * @param materielGauge      用于搜索的物料号
     * @param ifGlaze            上料状态
     * @param ifDelivery         发料状态
     * @param req
     * @return
     */
    @AutoLog(value = "制造中心-获取bom-分页列表查询")
    @ApiOperation(value = "制造中心-获取bom-分页列表查询", notes = "制造中心-制令单信息-分页列表查询")
    @GetMapping(value = "/listbom")
    public Result<?> listbom(MesCommandbillInfo mesCommandbillInfo,
                             @RequestParam(name = "oldCode", required = false) String oldCode,
                             @RequestParam(name = "newCode", required = false) String newCode,
                             @RequestParam(name = "choice", required = false) String choice,
                             @RequestParam(name = "planNum", required = false) String planNum,
                             @RequestParam(name = "materielGauge", required = false) String materielGauge,
                             @RequestParam(name = "ifGlaze", required = false) String ifGlaze,
                             @RequestParam(name = "ifDelivery", required = false) String ifDelivery,
                             @RequestParam(name = "wholid", required = false) String wholid,
                             HttpServletRequest req) {
        //如果原有制令单号不为空 转产制令单号为空，则进入退料模块
        if (StringUtils.isNotBlank(oldCode) && StringUtils.isBlank(newCode)) {
            //通过原有的制令单号，获取原有制令单id
            QueryWrapper<MesCommandbillInfo> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("commandbill_code", oldCode);
            MesCommandbillInfo commandbillInfo = mesCommandbillInfoService.getOne(queryWrapper);
            if (commandbillInfo == null) {
                return Result.error("找不到原有制令单信息！请检查！");
            }
            String oldCid = commandbillInfo.getId();//原有制令单id
            //进入制令单转产的退料模块，对比两条制令单所需的Bom数据，显示料号没有重复的Bom数据
            if (choice.equals("withdraw")) {
                QueryWrapper<MesCommandbillPitem> commandbillPitemQueryWrapper = new QueryWrapper<>();
                commandbillPitemQueryWrapper.eq("commandbill_id", oldCid);
                if (StringUtils.isNotBlank(materielGauge)) {
                    commandbillPitemQueryWrapper.like("materiel_gauge", materielGauge);
                }
                if (StringUtils.isNotBlank(wholid)) {
                    MesStorageWholesale wholesale = stockClient.findById(wholid);
                    if (wholesale == null && StringUtils.isBlank(wholesale.getProductCode())) {
                        return Result.error("未找到该二维码信息！");
                    }
                    //验证是不是替代料，是的话查询主料料号
                    List<MesChiefdataReplacematerial> replacematerials = systemClient.queryReplaceCode(commandbillInfo.getMechanismCode(), null, wholesale.getProductCode());
                    if (replacematerials.size() > 0) {
                        wholesale.setProductCode(replacematerials.get(0).getMainCode());
                    }
                    commandbillPitemQueryWrapper.eq("materiel_code", wholesale.getProductCode());
                }
                List<MesCommandbillPitem> commandbillPitems = mesCommandbillPitemService.list(commandbillPitemQueryWrapper);
                if (commandbillPitems.size() != 0) {
                    return Result.ok(commandbillPitems);
                } else {
                    return Result.error("找不到数据！请检查！");
                }
            }
        }
        //如果原有制令单号和转产制令单号不为空，则进入转产模块
        if (StringUtils.isNotBlank(oldCode) && StringUtils.isNotBlank(newCode)) {
            //通过原有的制令单号，获取原有制令单id
            QueryWrapper<MesCommandbillInfo> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("commandbill_code", oldCode);
            MesCommandbillInfo commandbillInfo = mesCommandbillInfoService.getOne(queryWrapper);
            if (commandbillInfo == null) {
                return Result.error("找不到原有制令单信息！请检查！");
            }
            String oldCid = commandbillInfo.getId();//原有制令单id
            //通过转产制令单号，获取转产制令单id与计划数量
            QueryWrapper<MesCommandbillInfo> wrapper = new QueryWrapper<>();
            wrapper.eq("commandbill_code", newCode);
            MesCommandbillInfo commandbillInfo1 = mesCommandbillInfoService.getOne(wrapper);
            if (commandbillInfo1 == null) {
                return Result.error("找不到转产制令单信息！请检查！");
            }
            String newCid = commandbillInfo1.getId();//转产制令单id
            String intendNum = commandbillInfo1.getPlantNum();//计划数量
            //通过转产制令单id，获取当前所需要的制令单BOM数据
            QueryWrapper<MesCommandbillPitem> pitemQueryWrapper = new QueryWrapper<>();
            pitemQueryWrapper.eq("commandbill_id", newCid);
            List<MesCommandbillPitem> commandbillPitemList = mesCommandbillPitemService.list(pitemQueryWrapper);
            ArrayList<String> mCodeList = new ArrayList<>();
            for (MesCommandbillPitem commandbillPitem : commandbillPitemList) {
                //获取原有制令单所需Bom的物料料号，并添加到mCodeList里
                String mCode = commandbillPitem.getMaterielCode();
                mCodeList.add(mCode);
            }
            //进入制令单转产的退料模块，对比两条制令单所需的Bom数据，显示料号没有重复的Bom数据
            if (choice.equals("withdraw")) {
                QueryWrapper<MesCommandbillPitem> commandbillPitemQueryWrapper = new QueryWrapper<>();
                commandbillPitemQueryWrapper.eq("commandbill_id", oldCid);
                if (mCodeList.size() > 0) {
                    commandbillPitemQueryWrapper.notIn("materiel_code", mCodeList);
                } else {
                    return Result.error("没有找到转产制令单的信息！请检查！");
                }
                List<MesCommandbillPitem> commandbillPitems = mesCommandbillPitemService.list(commandbillPitemQueryWrapper);
                if (commandbillPitems.size() != 0) {
                    if (StringUtils.isNotBlank(intendNum)) {
                        for (MesCommandbillPitem commandbillPitem : commandbillPitems) {
                            MesOrderProduce produce = transactionClient.queryMesProduceById(commandbillPitem.getProorderId());
                            BigDecimal grossNum = new BigDecimal(produce.getGrossAccount());//总数量
                            System.err.println(grossNum);
                            BigDecimal requireNum = new BigDecimal(commandbillPitem.getRequireNum());//需求数量
                            BigDecimal planNUm = new BigDecimal(intendNum);//计划数量
                            BigDecimal realNum = requireNum.multiply(planNUm.divide(grossNum, 3, RoundingMode.HALF_UP));//需求数量*计划数量/总数量
                            System.err.println(realNum);//真实数量
                            commandbillPitem.setRealNum(realNum.toString());
                            mesCommandbillPitemService.updateById(commandbillPitem);
                        }
                    }
                    return Result.ok(commandbillPitems);
                } else {
                    return Result.error("找不到数据！请检查！");
                }
                //进入制令单转产的退料模块，对比两条制令单所需的Bom数据，显示料号重复的Bom数据
            } else if (choice.equals("change")) {
                QueryWrapper<MesCommandbillPitem> commandbillPitemQueryWrapper = new QueryWrapper<>();
                commandbillPitemQueryWrapper.eq("commandbill_id", oldCid);
                if (StringUtils.isNotBlank(materielGauge)) {
                    commandbillPitemQueryWrapper.like("materiel_gauge", materielGauge);
                }

                if (StringUtils.isNotBlank(wholid)) {
                    MesStorageWholesale wholesale = stockClient.findById(wholid);
                    if (wholesale == null && StringUtils.isBlank(wholesale.getProductCode())) {
                        return Result.error("未找到该二维码信息！");
                    }
                    //验证是不是替代料，是的话查询主料料号
                    List<MesChiefdataReplacematerial> replacematerials = systemClient.queryReplaceCode(commandbillInfo.getMechanismCode(), null, wholesale.getProductCode());
                    if (replacematerials.size() > 0) {
                        wholesale.setProductCode(replacematerials.get(0).getMainCode());
                    }
                    commandbillPitemQueryWrapper.eq("materiel_code", wholesale.getProductCode());
                }

                if (mCodeList.size() > 0) {
                    commandbillPitemQueryWrapper.in("materiel_code", mCodeList);
                } else {
                    return Result.error("没有找到转产制令单的信息！请检查！");
                }
                List<MesCommandbillPitem> commandbillPitems = mesCommandbillPitemService.list(commandbillPitemQueryWrapper);
                if (commandbillPitems.size() != 0) {
                    if (StringUtils.isNotBlank(intendNum)) {
                        for (MesCommandbillPitem commandbillPitem : commandbillPitems) {
                            MesOrderProduce produce = transactionClient.queryMesProduceById(commandbillPitem.getProorderId());
                            BigDecimal grossNum = new BigDecimal(produce.getGrossAccount());
                            System.err.println(grossNum);
                            BigDecimal requireNum = new BigDecimal(commandbillPitem.getRequireNum());
                            BigDecimal planNUm = new BigDecimal(intendNum);
                            BigDecimal realNum = requireNum.multiply(planNUm.divide(grossNum, 3, RoundingMode.HALF_UP));
                            System.err.println(realNum);
                            commandbillPitem.setRealNum(realNum.toString());
                            mesCommandbillPitemService.updateById(commandbillPitem);
                        }
                    }
                    return Result.ok(commandbillPitems);
                } else {
                    return Result.error("找不到数据！请检查！");
                }
            }
        }
        if (StringUtils.isNotBlank(ifDelivery)) {//进入了制令单发料
            QueryWrapper<MesCommandbillPitem> queryWrapper = new QueryWrapper<>();
            if (StringUtils.isNotBlank(materielGauge)) {
                queryWrapper.eq("commandbill_id", mesCommandbillInfo.getId());
                queryWrapper.eq("materiel_code", materielGauge);
            } else if (StringUtils.isNotBlank(ifDelivery)) {
                queryWrapper.eq("commandbill_id", mesCommandbillInfo.getId());
                queryWrapper.eq("if_delivery", ifDelivery);
            } else {
                queryWrapper.eq("commandbill_id", mesCommandbillInfo.getId());
            }
            List<MesCommandbillPitem> commandbillPitemList = mesCommandbillPitemService.list(queryWrapper);
            if (commandbillPitemList.size() != 0) {
                if (StringUtils.isNotBlank(planNum)) {
                    for (int i = 0; i < commandbillPitemList.size(); i++) {

                        MesCommandbillPitem commandbillPitem = commandbillPitemList.get(i);
                        //				 	//通过料号更新库存数据
                        //					 MesStockManage stockManage = stockClient.queryByMcode(commandbillPitem.getMaterielCode());
                        //					 BigDecimal stockNum = new BigDecimal(stockManage.getStockNum());
                        //					 BigDecimal commandStockNum = new BigDecimal(commandbillPitem.getStockNum());
                        //					 if(stockNum.compareTo(commandStockNum) != 0){
                        //						 UpdateWrapper<MesCommandbillPitem> updateWrapper = new UpdateWrapper<>();
                        //						 updateWrapper.eq("materiel_code",commandbillPitem.getMaterielCode()).eq("commandbill_id",commandbillPitem.getCommandbillId());
                        //						 commandbillPitem.setStockNum(stockNum.toString());
                        //						 mesCommandbillPitemService.update(commandbillPitem,updateWrapper);
                        //					 }
                        MesOrderProduce produce = transactionClient.queryMesProduceById(commandbillPitem.getProorderId());
                        BigDecimal grossNum = new BigDecimal(produce.getGrossAccount());
                        System.err.println(grossNum);
                        BigDecimal requireNum = new BigDecimal(commandbillPitem.getRequireNum());
                        BigDecimal planNUm = new BigDecimal(planNum);
                        BigDecimal realNum = requireNum.multiply(planNUm.divide(grossNum, 3, RoundingMode.HALF_UP));
                        System.err.println(realNum);
                        commandbillPitem.setRealNum(realNum.toString());
                        mesCommandbillPitemService.updateById(commandbillPitem);

                        //根据bomitem获取客户料号
                        if (StringUtils.isNotBlank(commandbillPitem.getMaterielCode())) {
                            MesChiefdataBomitem materielCodeitem = systemClient.getMCodebomitemForIn(commandbillPitem.getMaterielCode().toString());
                            if (materielCodeitem != null && StringUtils.isNotBlank(materielCodeitem.getClientCode())) {
                                commandbillPitemList.get(i).setClientCode(materielCodeitem.getClientCode());
                            }
                        }
                    }
                }
            } else {
                return Result.ok("未找到该数据！");
            }
            return Result.ok(commandbillPitemList);

        } else if (StringUtils.isNotBlank(ifGlaze)) {//进入制令单上料
            QueryWrapper<MesCommandbillPitem> queryWrapper = new QueryWrapper<>();
            if (StringUtils.isNotBlank(materielGauge)) {
                queryWrapper.eq("commandbill_id", mesCommandbillInfo.getId()).like("materiel_gauge", materielGauge);
            } else if (StringUtils.isNotBlank(ifGlaze)) {
                queryWrapper.eq("commandbill_id", mesCommandbillInfo.getId()).eq("if_glaze", ifGlaze);
            } else {
                queryWrapper.eq("commandbill_id", mesCommandbillInfo.getId());
            }
            List<MesCommandbillPitem> commandbillPitemList = mesCommandbillPitemService.list(queryWrapper);
            if (commandbillPitemList.size() != 0) {
                if (StringUtils.isNotBlank(planNum)) {
                    for (MesCommandbillPitem commandbillPitem : commandbillPitemList) {
//				 	//通过料号更新库存数据
//					 MesStockManage stockManage = stockClient.queryByMcode(commandbillPitem.getMaterielCode());
//					 BigDecimal stockNum = new BigDecimal(stockManage.getStockNum());
//					 BigDecimal commandStockNum = new BigDecimal(commandbillPitem.getStockNum());
//					 if(stockNum.compareTo(commandStockNum) != 0){
//						 UpdateWrapper<MesCommandbillPitem> updateWrapper = new UpdateWrapper<>();
//						 updateWrapper.eq("materiel_code",commandbillPitem.getMaterielCode()).eq("commandbill_id",commandbillPitem.getCommandbillId());
//						 commandbillPitem.setStockNum(stockNum.toString());
//						 mesCommandbillPitemService.update(commandbillPitem,updateWrapper);
//					 }
                        MesOrderProduce produce = transactionClient.queryMesProduceById(commandbillPitem.getProorderId());
                        BigDecimal grossNum = new BigDecimal(produce.getGrossAccount());
                        System.err.println(grossNum);
                        BigDecimal requireNum = new BigDecimal(commandbillPitem.getRequireNum());
                        BigDecimal planNUm = new BigDecimal(planNum);
                        BigDecimal realNum = requireNum.multiply(planNUm.divide(grossNum, 3, RoundingMode.HALF_UP));
                        System.err.println(realNum);
                        commandbillPitem.setRealNum(realNum.toString());
                        mesCommandbillPitemService.updateById(commandbillPitem);
                    }
                }
            } else {
                return Result.ok("上料已完成！");
            }
            return Result.ok(commandbillPitemList);

        } else {
            return Result.ok();
        }
    }


    @GetMapping(value = "/print")
    public Result<?> print(@RequestParam(name = "id", required = true) String id,
                           @RequestParam(name = "printNum", required = true) int printNum) {
        MesCommandbillInfo commandbillInfo = mesCommandbillInfoService.getById(id);
        if (StringUtils.isBlank(commandbillInfo.getCommandbillCode())) {
            return Result.error("制令单号不能为空！请检查！");
        }
        for (int i = 0; i < printNum; i++) {
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
            String dateString = formatter.format(new Date());
            commandbillInfo.setPrintTime(dateString);
            // 获取随机字符串
            SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
            int random = RandomUtils.nextInt(90) + 10;
            String randomNo = format.format(new Date()) + random;

            //标签打印，通过打印类型，远程调用主数据模块，获取到打印模块的数据
            String mobileType = "制令单打印";
            MesPrintModel printModel = systemClient.queryByPrintType(mobileType);
            if (printModel != null) {
                try {
                    executor.execute(new Runnable() {
                        @Override
                        public void run() {
                            //coHead打印的实体类
                            conHead conHead = new conHead();
                            //二维码字段，存放制令单id
//							 conHead.setConBy1(commandbillInfo.getId());
                            //二维码字段，存放制令单号
                            conHead.setConBy1(commandbillInfo.getCommandbillCode());
                            //随机字符串，用于文件的命名
                            conHead.setOrderNo(randomNo);
                            conHead.setConNo(randomNo);
                            // contempPath：打印模版的url路径，一般是word文档，存在minio里
                            conHead.setContempPath(printModel.getPrintModel());
                            List<conmap> conmapList = new ArrayList<>();//打印字段
                            //将批号交易类实体转成map,以K,V形式存取
                            Map map = JSON.parseObject(JSON.toJSONString(commandbillInfo), Map.class);
                            System.err.println(map);
                            //遍历Map，取到Key和Value
                            map.forEach((key, value) -> {
                                System.err.println("key=" + key + ",value=" + value);
                                //conmap 打印字段实体类
                                conmap conmap = new conmap();
                                //根据key,将打印模版的{key}转换成value
                                conmap.setConKey(key.toString());
                                conmap.setConValue(value.toString());
                                conmapList.add(conmap);
                            });
                            conHead.setConmapList(conmapList);
                            try {
                                //调用打印功能，printModel.getPrintServeaddress()为调用远程打印的服务器地址
                                mesUtil.gencontract(printModel.getPrintServeaddress(), conHead);
                            } catch (Exception e) {

                            }
                        }
                    });
                } catch (Exception e) {

                }

            } else {
                return Result.error("没有找到打印模版的数据！请检查！");
            }
        }
        return Result.ok("没错！就是这里！");
    }

    /**
     * 添加
     *
     * @param mesCommandbillInfo
     * @return
     */
    @AutoLog(value = "制造中心-制令单信息-添加")
    @ApiOperation(value = "制造中心-制令单信息-添加", notes = "制造中心-制令单信息-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody MesCommandbillInfo mesCommandbillInfo) {
        MesWorkbillInfo mesWorkbillInfo = mesWorkbillInfoService.getById(mesCommandbillInfo.getWorkbillId());
        if (mesWorkbillInfo != null) {
            mesCommandbillInfo.setControlType("正常");//管控类型
            mesCommandbillInfo.setExpectBegintime(mesWorkbillInfo.getExpectBegintime());//计划开始时间
            mesCommandbillInfo.setExpectFinishtime(mesWorkbillInfo.getExpectFinishtime());//计划结束时间
            mesCommandbillInfo.setArriveTime(new Date());//下达时间
            mesCommandbillInfo.setNotes(mesWorkbillInfo.getNotes());//备注
            mesCommandbillInfo.setDeliveryState("未完成");
            mesCommandbillInfo.setGlazeState("未完成");
            mesCommandbillInfo.setInputState("未完成");
            mesCommandbillInfo.setFirstState("未完成");//首件状态
            mesCommandbillInfo.setUninputNum(mesWorkbillInfo.getPlantNum());//未入库数量
            mesCommandbillInfo.setState("未完成");
            mesCommandbillInfo.setCheckState("未完成");

            if (StringUtils.isNotBlank(mesWorkbillInfo.getProduceId())) {
                String orderId = mesWorkbillInfo.getProduceId();
                mesCommandbillInfo.setProduceId(orderId);//生产订单id
                mesCommandbillInfoService.save(mesCommandbillInfo);
                List<MesProduceItem> produceItemList = transactionClient.listMesProduceItemByOrderId(orderId);
                if (produceItemList.size() != 0) {
                    for (MesProduceItem produceItem : produceItemList) {
                        MesCommandbillPitem commandbillPitem = new MesCommandbillPitem();
                        BeanUtils.copyProperties(produceItem, commandbillPitem);
                        commandbillPitem.setOrderitemId(commandbillPitem.getId());//生产订单子表id
                        commandbillPitem.setCommandbillCode(mesCommandbillInfo.getCommandbillCode());//制令单号
                        commandbillPitem.setCommandbillId(mesCommandbillInfo.getId());//制令单id
                        commandbillPitem.setId(null);//主键设置为null
                        commandbillPitem.setCreateBy(null);//创建人设置为null
                        commandbillPitem.setCreateTime(null);//创建时间设置为null
                        commandbillPitem.setDeliveryNum("0");//发料数量
                        commandbillPitem.setUnglazeNum("0");//上料数量
                        commandbillPitem.setWithdrawNum("0");//退料数量
                        mesCommandbillPitemService.save(commandbillPitem);
                    }
                } else {
                    return Result.error("找不到生产订单子表的数据！请检查！");
                }
            } else {
                return Result.error("生产订单ID为空！请检查！");
            }
            return Result.ok("制令单添加成功！");
        } else {
            return Result.error("查不到工单数据!请检查！");
        }
//		if(StringUtils.isNotBlank(mesCommandbillInfo.getPlantNum())){
//			mesCommandbillInfo.setUninputNum(mesCommandbillInfo.getPlantNum());//计划数量
//		}
//		mesCommandbillInfoService.save(mesCommandbillInfo);
//		return Result.ok("添加成功！");
    }

    /**
     * 生产订单，一键生成制令单，调用的是这里的接口
     *
     * @param mesOrderProduce
     * @return
     * @throws InterruptedException
     */
    @PostMapping(value = "/produceAddInstrution")
    public String produceAddInstrution(@RequestBody MesOrderProduce mesOrderProduce) throws InterruptedException {
//		 System.err.println("开始sleep");
//		Thread.sleep(10000);
//		 System.err.println("调用开始");
        String produceState = "待发料";
        if (produceState.equals(mesOrderProduce.getState()) || "缺料".equals(mesOrderProduce.getState())) {
            if (StringUtils.isNotBlank(mesOrderProduce.getProduceGrade())) {
                String produceGrade = mesOrderProduce.getProduceGrade();
                QueryWrapper<MesWorkbillInfo> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("workbill_code", mesOrderProduce.getOrderCode()).eq("produce_id", mesOrderProduce.getId());
                MesWorkbillInfo workbillInfo = mesWorkbillInfoService.getOne(queryWrapper);
                if (workbillInfo == null) {
                    //新增制令单
                    String[] pGrade = produceGrade.split(",");
                    String[] pline = mesOrderProduce.getLineSort().split(",");
                    int count1 = 0;
                    for (String s : pGrade) {
                        count1 += 1;
                        //实例化format，格式为“000”
                        Format f1 = new DecimalFormat("000");
                        //将1变为001
                        String count = f1.format(count1);

                        //新增工单
                        MesWorkbillInfo mesWorkbillInfo = new MesWorkbillInfo();
                        mesWorkbillInfo.setProduceId(mesOrderProduce.getId());//生产订单id
                        mesWorkbillInfo.setProduceCode(mesOrderProduce.getOrderCode());//生产单号
                        mesWorkbillInfo.setWorkbillCode(mesOrderProduce.getOrderCode() + "-" + count);//工单号=生产单号+编号
                        mesWorkbillInfo.setProduceGrade(s);//生产阶别
                        mesWorkbillInfo.setMechanismCode(mesOrderProduce.getMaterielCode());//成品料号
                        mesWorkbillInfo.setMechanismName(mesOrderProduce.getMaterielName());//成品名称
                        mesWorkbillInfo.setGague(mesOrderProduce.getGauge());//规格
                        mesWorkbillInfo.setPlantNum(mesOrderProduce.getGrossAccount());//数量
                        mesWorkbillInfo.setAutomaticCommandbill("是");
                        mesWorkbillInfo.setClient(mesOrderProduce.getClient());//客户
                        mesWorkbillInfo.setExpectBegintime(mesOrderProduce.getPlanStart());//计划开始时间
                        mesWorkbillInfo.setRealBegintime(mesOrderProduce.getConfirmStart());//实际开始时间
                        mesWorkbillInfo.setExpectFinishtime(mesOrderProduce.getPlanEnd());//计划结束时间
                        mesWorkbillInfo.setRealFinishtime(mesOrderProduce.getConfirmEnd());//实际结束时间
                        //判断是否有该生产工单
                        QueryWrapper<MesWorkbillInfo> queryWrapper5 = new QueryWrapper<>();
                        queryWrapper5.eq("workbill_code", mesWorkbillInfo.getWorkbillCode());
                        List<MesWorkbillInfo> list = mesWorkbillInfoService.list(queryWrapper5);
                        if (list.size() > 0) {
                            return "已存在该工单";
                        }
                        //保存
                        mesWorkbillInfoService.save(mesWorkbillInfo);

                        if (s.equals("SMT")) {
                            String linesort = "";
                            for (String line : pline) {
                                if (line.indexOf(s) != -1) {
                                    linesort = line;
                                }
                            }
                            //新增制令单BOM
                            List<MesProduceItem> produceItemList = transactionClient.listMesProduceItemByOrderId(mesOrderProduce.getId());
                            for (MesProduceItem productitem : produceItemList) {
                                if (StringUtils.isBlank(productitem.getMaterielGrade())) {
                                    //删除已创建的生产工单
                                    mesWorkbillInfoService.removeById(mesWorkbillInfo.getId());
                                    return "需指定生产订单子表中物料的物料阶别！";
                                }
                            }
                            //新增制令单
                            MesCommandbillInfo commandbillInfo = new MesCommandbillInfo();
                            commandbillInfo.setProduceId(mesOrderProduce.getId());//生产订单id
                            commandbillInfo.setWorkbillId(mesWorkbillInfo.getId());//工单id
                            commandbillInfo.setWorkbillCode(mesWorkbillInfo.getWorkbillCode());//工单号
                            commandbillInfo.setCommandbillCode(mesOrderProduce.getOrderCode() + "-" + count);//制令单号
                            commandbillInfo.setControlType("正常");//管控类型
                            commandbillInfo.setProduceGrade("SMT");//生产阶别
                            commandbillInfo.setLineType(linesort);//线别
                            commandbillInfo.setMechanismCode(mesOrderProduce.getMaterielCode());//成品料号
                            commandbillInfo.setMechanismName(mesOrderProduce.getMaterielName());//成品名称
                            commandbillInfo.setGague(mesOrderProduce.getGauge());//规格
                            commandbillInfo.setPlantNum(mesOrderProduce.getGrossAccount());//数量
                            commandbillInfo.setUninputNum(mesOrderProduce.getGrossAccount());//未入库数量
                            commandbillInfo.setExpectBegintime(mesOrderProduce.getPlanStart());//计划开始时间
                            commandbillInfo.setExpectFinishtime(mesOrderProduce.getPlanEnd());//计划结束时间
                            commandbillInfo.setArriveTime(new Date());//下达时间
                            commandbillInfo.setGlazeRemind(mesOrderProduce.getGlazeRemind());//上料提醒
                            commandbillInfo.setClientName(mesOrderProduce.getClient());//客户
                            commandbillInfo.setState("未完成");//状态
                            commandbillInfo.setDeliveryState("未完成");//发料未完成
                            commandbillInfo.setGlazeState("未完成");//上料未完成
                            commandbillInfo.setInputState("未完成");//入库状态
                            commandbillInfo.setCheckState("未完成");
                            commandbillInfo.setFirstState("未完成");//首件状态
                            mesCommandbillInfoService.save(commandbillInfo);

                            //更新在线料表主表数据
                            mesOnlineMaterieltableMainService.updateMain(mesOrderProduce.getMaterielCode(), linesort);

                            if (produceItemList.size() != 0) {
                                for (MesProduceItem produceItem : produceItemList) {
                                    if (!s.equals(produceItem.getMaterielGrade())) {
                                        //不同生产阶别的不在同一个制令单
                                        continue;
                                    }
                                    MesCommandbillPitem commandbillPitem = new MesCommandbillPitem();
                                    BeanUtils.copyProperties(produceItem, commandbillPitem);
                                    commandbillPitem.setOrderitemId(commandbillPitem.getId());//生产订单子表id
                                    commandbillPitem.setCommandbillCode(commandbillInfo.getCommandbillCode());//制令单号
                                    commandbillPitem.setCommandbillId(commandbillInfo.getId());//制令单id
                                    commandbillPitem.setId(null);//主键设置为null
                                    commandbillPitem.setDeliveryNum("0");//发料数量
                                    commandbillPitem.setUnglazeNum("0");//上料数量
                                    commandbillPitem.setConsumeNum("0");//消耗数量
                                    commandbillPitem.setWithdrawNum("0");//退料数量
                                    commandbillPitem.setIfDelivery("未发料");//发料状态
                                    commandbillPitem.setIfGlaze("未上料");//上料状态
                                    mesCommandbillPitemService.save(commandbillPitem);
                                }
                            }
                        } else {
                            String linesort = "";
                            for (String line : pline) {
                                if (line.indexOf(s) != -1) {
                                    linesort = line;
                                }
                            }
                            //新增制令单BOM
                            List<MesProduceItem> produceItemList = transactionClient.listMesProduceItemByOrderId(mesOrderProduce.getId());
                            for (MesProduceItem productitem : produceItemList) {
                                if (StringUtils.isBlank(productitem.getMaterielGrade())) {
                                    //删除已创建的生产工单
                                    mesWorkbillInfoService.removeById(mesWorkbillInfo.getId());
                                    return "需指定生产订单子表中物料的物料阶别！";
                                }
                            }
                            //新增制令单
                            MesCommandbillInfo commandbillInfo = new MesCommandbillInfo();
                            commandbillInfo.setProduceId(mesOrderProduce.getId());//生产订单id
                            commandbillInfo.setWorkbillId(mesWorkbillInfo.getId());//工单id
                            commandbillInfo.setWorkbillCode(mesWorkbillInfo.getWorkbillCode());//工单号
                            commandbillInfo.setCommandbillCode(mesOrderProduce.getOrderCode() + "-" + count);//制令单号
                            commandbillInfo.setControlType("正常");//管控类型
                            commandbillInfo.setProduceGrade(s);//生产阶别
                            commandbillInfo.setLineType(linesort);//线别
                            commandbillInfo.setMechanismCode(mesOrderProduce.getMaterielCode());//成品料号
                            commandbillInfo.setMechanismName(mesOrderProduce.getMaterielName());//成品名称
                            commandbillInfo.setGague(mesOrderProduce.getGauge());//规格
                            commandbillInfo.setPlantNum(mesOrderProduce.getGrossAccount());//数量
                            commandbillInfo.setUninputNum(mesOrderProduce.getGrossAccount());//未入库数量
                            commandbillInfo.setExpectBegintime(mesOrderProduce.getPlanStart());//计划开始时间
                            commandbillInfo.setExpectFinishtime(mesOrderProduce.getPlanEnd());//计划结束时间
                            commandbillInfo.setArriveTime(new Date());//下达时间
                            commandbillInfo.setGlazeRemind(mesOrderProduce.getGlazeRemind());//上料提醒
                            commandbillInfo.setClientName(mesOrderProduce.getClient());//客户
                            commandbillInfo.setState("未完成");//状态
                            commandbillInfo.setDeliveryState("未完成");//发料未完成
                            commandbillInfo.setGlazeState("未完成");//上料未完成
                            commandbillInfo.setInputState("未完成");//入库状态
                            commandbillInfo.setCheckState("未完成");
                            commandbillInfo.setFirstState("未完成");//首件状态
                            mesCommandbillInfoService.save(commandbillInfo);

                            //更新在线料表主表数据
                            mesOnlineMaterieltableMainService.updateMain(mesOrderProduce.getMaterielCode(), linesort);

                            if (produceItemList.size() != 0) {
                                for (MesProduceItem produceItem : produceItemList) {
                                    if (!s.equals(produceItem.getMaterielGrade())) {
                                        //不同生产阶别的不在同一个制令单
                                        continue;
                                    }
                                    MesCommandbillPitem commandbillPitem = new MesCommandbillPitem();
                                    BeanUtils.copyProperties(produceItem, commandbillPitem);
                                    commandbillPitem.setOrderitemId(commandbillPitem.getId());//生产订单子表id
                                    commandbillPitem.setCommandbillCode(commandbillInfo.getCommandbillCode());//制令单号
                                    commandbillPitem.setCommandbillId(commandbillInfo.getId());//制令单id
                                    commandbillPitem.setId(null);//主键设置为null
                                    commandbillPitem.setDeliveryNum("0");//发料数量
                                    commandbillPitem.setUnglazeNum("0");//上料数量
                                    commandbillPitem.setConsumeNum("0");//消耗数量
                                    commandbillPitem.setWithdrawNum("0");//退料数量
                                    commandbillPitem.setIfDelivery("未发料");//发料状态
                                    commandbillPitem.setIfGlaze("未上料");//上料状态
                                    mesCommandbillPitemService.save(commandbillPitem);
                                }
                            }
                        }
                    }

                } else {
                    return "该生产订单已经生成工单和制令单";
                }

            } else {
                return "生产阶别为空！请检查！";
            }
        } else {
            return "状态有误！请重新选择生产订单！";
        }
        return "一键生成制令单成功！！";
    }

    /**
     * 制造中心-制令单信息-app结束入库
     *
     * @param id 制令单id
     * @return
     */
    @AutoLog(value = "制造中心-制令单信息-app结束入库")
    @ApiOperation(value = "制造中心-制令单信息-app结束入库", notes = "制造中心-制令单信息-app结束入库")
    @GetMapping(value = "/endStorage")
    public Result<?> endStorage(@RequestParam(name = "id", required = true) String id) {
        MesCommandbillInfo info = mesCommandbillInfoService.getById(id);
        if (info == null) {
            return Result.error("未找到该制令单信息！");
        }
        info.setInputState("不入库");
        mesCommandbillInfoService.updateById(info);
        return Result.ok("操作成功!");
    }

    /**
     * 制造中心-制令单信息-app转线
     *
     * @param id       制令单id
     * @param linetype 线别
     * @return
     */
    @AutoLog(value = "制造中心-制令单信息-app转线")
    @ApiOperation(value = "制造中心-制令单信息-app转线", notes = "制造中心-制令单信息-app转线")
    @GetMapping(value = "/transferLine")
    public Result<?> transferLine(@RequestParam(name = "id", required = true) String id,
                                  @RequestParam(name = "linetype", required = true) String linetype) {
        MesCommandbillInfo info = mesCommandbillInfoService.getById(id);
        if (info == null) {
            return Result.error("未找到该制令单信息！");
        }

        MesOrderProduce mesOrderProduce = new MesOrderProduce();
        mesOrderProduce.setId(info.getProduceId());
        mesOrderProduce.setLineSort(linetype);
        transactionClient.updatemesOrderProduce(mesOrderProduce);
        info.setLineType(linetype);
        mesCommandbillInfoService.updateById(info);
        return Result.ok("转线成功!");
    }

    /**
     * 编辑
     *
     * @param mesCommandbillInfo
     * @return
     */
    @AutoLog(value = "制造中心-制令单信息-编辑")
    @ApiOperation(value = "制造中心-制令单信息-编辑", notes = "制造中心-制令单信息-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody MesCommandbillInfo mesCommandbillInfo) {
        if (StringUtils.isNotBlank(mesCommandbillInfo.getPlantNum())) {
            mesCommandbillInfo.setUninputNum(mesCommandbillInfo.getPlantNum());
        }
        String id = mesCommandbillInfo.getId();
        String commandbillCode = mesCommandbillInfo.getCommandbillCode();
        UpdateWrapper<MesCommandbillPitem> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("commandbill_id", id).set("commandbill_code", commandbillCode);
        mesCommandbillPitemService.update(updateWrapper);
        mesCommandbillInfoService.updateById(mesCommandbillInfo);
        return Result.ok("编辑成功!");
    }

    /**
     * 用于远程调用，编辑制令单
     *
     * @param mesCommandbillInfo
     * @return
     */
    @PutMapping(value = "/editCommand")
    public boolean editCommand(@RequestBody MesCommandbillInfo mesCommandbillInfo) {
        return mesCommandbillInfoService.updateById(mesCommandbillInfo);
    }

    @GetMapping(value = "/getInfoByLine")
    public List<MesCommandbillInfo> getInfoByLine() {
        QueryWrapper<MesCommandbillInfo> w1 = new QueryWrapper();
        w1.select("line_type", "sum(plant_num) as plant_num");
        w1.eq("input_state", "未完成");
        w1.groupBy("line_type");
        w1.orderByDesc("sum(plant_num)");
        List<MesCommandbillInfo> list = mesCommandbillInfoService.list(w1);
        return list;
    }

    @GetMapping(value = "/getInfoTotalByLine")
    public MesCommandbillInfo getInfoTotalByLine() {
        QueryWrapper<MesCommandbillInfo> w1 = new QueryWrapper();
        w1.select("sum(plant_num) as plant_num");
        w1.eq("input_state", "未完成");
        MesCommandbillInfo list = mesCommandbillInfoService.getOne(w1);
        return list;
    }

    @GetMapping(value = "/queryByCode")
    public MesCommandbillInfo queryByCode(@RequestParam(name = "code", required = true) String code) {
        QueryWrapper<MesCommandbillInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("commandbill_code", code);
        MesCommandbillInfo mesCommandbillInfo = mesCommandbillInfoService.list(queryWrapper).get(0);

        return mesCommandbillInfo;
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "制造中心-制令单信息-通过id删除")
    @ApiOperation(value = "制造中心-制令单信息-通过id删除", notes = "制造中心-制令单信息-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        QueryWrapper<MesCommandbillPitem> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("commandbill_id", id);
        mesCommandbillPitemService.remove(queryWrapper);
        mesCommandbillInfoService.removeById(id);
        return Result.ok("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "制造中心-制令单信息-批量删除")
    @ApiOperation(value = "制造中心-制令单信息-批量删除", notes = "制造中心-制令单信息-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.mesCommandbillInfoService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.ok("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "制造中心-制令单信息-通过id查询")
    @ApiOperation(value = "制造中心-制令单信息-通过id查询", notes = "制造中心-制令单信息-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        MesCommandbillInfo mesCommandbillInfo = mesCommandbillInfoService.getById(id);
        if (mesCommandbillInfo == null) {
            return Result.error("未找到对应数据");
        }
        return Result.ok(mesCommandbillInfo);
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "制令单BOM项目通过主表ID查询")
    @ApiOperation(value = "制令单BOM项目主表ID查询", notes = "制令单BOM项目-通主表ID查询")
    @GetMapping(value = "/queryMesCommandbillPitemByMainId")
    public Result<?> queryMesCommandbillPitemListByMainId(@RequestParam(name = "id", required = true) String id) {
        List<MesCommandbillPitem> mesCommandbillPitemList = mesCommandbillPitemService.selectByMainId(id);
        return Result.ok(mesCommandbillPitemList);
    }

    /**
     * 通过code查询
     *
     * @param code
     * @return
     */
    @AutoLog(value = "制造中心-制令单信息-通过code查询")
    @ApiOperation(value = "制造中心-制令单信息-通过code查询", notes = "制造中心-制令单信息-通过code查询")
    @GetMapping(value = "/queryByCommandBillCode")
    public Result<?> queryByCommandBillCode(@RequestParam(name = "code") String code) {
        QueryWrapper<MesCommandbillInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("commandbill_code", code);
        MesCommandbillInfo mesCommandbillInfo = mesCommandbillInfoService.list(queryWrapper).get(0);
        return Result.ok(mesCommandbillInfo);
    }

    /**
     * 上料时，通过成品料号、物料料号、线别，显示该盘物料的料表信息，包括料站、通道等
     *
     * @param id
     * @return
     */
    @AutoLog(value = "制造中心—在线料表-通过ID查询")
    @ApiOperation(value = "制造中心—在线料表-通过制令单Id查询", notes = "制造中心—在线料表-通过制令单Id查询")
    @GetMapping(value = "/getOnlineMaterirlById")
    public Result<?> getOnlineMaterirlById(@RequestParam(name = "id", required = true) String id,
                                           @RequestParam(name = "wareId", required = true) String wareId) {
        MesStorageWholesale wholeinfo = stockClient.findById(wareId);
        if (wholeinfo == null) {
            mesCommandbillInfoService.recordErrorOperation("/produce/mesCommandbillInfo/getOnlineMaterirlById", "制令单上料", "制造中心—在线料表-通过制令单Id查询", "没有找到该二维码数据！请检查！", id);
            return Result.error("没有找到该二维码数据！请检查！");
        }
        String productCode = wholeinfo.getProductCode();
        //替代料验证
        MesCommandbillInfo commandbillinfo = mesCommandbillInfoService.getById(id);
        List<MesChiefdataReplacematerial> replacematerials = systemClient.queryReplaceCode(commandbillinfo.getMechanismCode(), null, wholeinfo.getProductCode());
        if (replacematerials.size() > 0) {
            wholeinfo.setProductCode(replacematerials.get(0).getMainCode());
        }
        //通过制令单的ID查出bom数据,验证是否在该物料中有该数据
        QueryWrapper<MesCommandbillPitem> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("commandbill_id", id);
        queryWrapper1.eq("materiel_code", wholeinfo.getProductCode());
        List<MesCommandbillPitem> commandbillPitems = mesCommandbillPitemService.list(queryWrapper1);
        commandbillPitems.forEach(System.out::println);
        if (commandbillPitems.size() > 0) {
            //在线料表
            List<MesOnlineMaterieltable> onlineMaterieltables = new ArrayList<>();
            //通过查询
            for (MesCommandbillPitem commandbillPitem : commandbillPitems) {
                String commandbillId = commandbillPitem.getCommandbillId();//制令单id
                System.out.println("制令单id:" + commandbillId);
                //通过制令单id,获取制令单的数据
                MesCommandbillInfo commandbillInfo = mesCommandbillInfoService.getById(commandbillId);

                if (commandbillInfo != null) {
                    if (StringUtils.isNotBlank(commandbillInfo.getMechanismCode())) {
                        String pCode = commandbillInfo.getMechanismCode();//成品料号
                        String lineType = commandbillInfo.getLineType();//线别
                        String mCode = commandbillPitem.getMaterielCode();//物料料号
                        System.out.println("成品料号:" + pCode + "物料料号:" + mCode);
                        //通过成品料号、物料料号、线别，显示该盘物料的料表信息
                        QueryWrapper<MesOnlineMaterieltable> queryWrapper = new QueryWrapper<>();
                        queryWrapper.eq("product_code", pCode).eq("materiel_code", mCode).eq("line_type", lineType);
                        List<MesOnlineMaterieltable> list = mesOnlineMaterieltableService.list(queryWrapper);
                        //根据传过来的wareid进行验证
                        if (list.size() > 0) {
                            //根据在线料表同物料多通道情况
                            for (MesOnlineMaterieltable mesOnlineMaterieltable : list) {
                                String produceLine = mesOnlineMaterieltable.getLineType();//线别
                                System.out.println("线别produceLine:" + produceLine + " 线别lineTpe:" + lineType);
                                if (produceLine.equals(lineType)) {
                                    if (onlineMaterieltables.size() > 0) {
                                        String passage = onlineMaterieltables.get(0).getPassage();
                                        onlineMaterieltables.get(0).setPassage(passage + "," + mesOnlineMaterieltable.getPassage());
                                    } else {
                                        onlineMaterieltables.add(mesOnlineMaterieltable);
                                    }
                                }
                            }
                        }

                    }
                } else {
                    mesCommandbillInfoService.recordErrorOperation("/produce/mesCommandbillInfo/getOnlineMaterirlById", "制令单上料", "制造中心—在线料表-通过制令单Id查询", "没有找到" + commandbillPitem.getCommandbillCode() + "的制令单信息！请检查！", id);
                    return Result.error("没有找到" + commandbillPitem.getCommandbillCode() + "的制令单信息！请检查！");
                }
            }
            if (onlineMaterieltables.size() > 0) {
                if (replacematerials.size() > 0) {
                    onlineMaterieltables.get(0).setMaterielCode(productCode);
                }
                return Result.ok(onlineMaterieltables);
            } else {
                mesCommandbillInfoService.recordErrorOperation("/produce/mesCommandbillInfo/getOnlineMaterirlById", "制令单上料", "制造中心—在线料表-通过制令单Id查询", "没有找到对应的在线料表数据！请检查！", id);
                return Result.error("没有找到对应的在线料表数据！请检查！");
            }
        } else {
            mesCommandbillInfoService.recordErrorOperation("/produce/mesCommandbillInfo/getOnlineMaterirlById", "制令单上料", "制造中心—在线料表-通过制令单Id查询", "没有找到制令单BOM数据！请检查！", id);
            return Result.error("没有找到制令单BOM数据！请检查！");
        }
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @GetMapping(value = "/getById")
    public MesCommandbillInfo getById(@RequestParam(name = "id", required = true) String id) {
        MesCommandbillInfo mesCommandbillInfo = mesCommandbillInfoService.getById(id);
        return mesCommandbillInfo;
    }

    /**
     * 远程调用，根据制令单发料数量修改生产订单状态
     *
     * @param commandBillId
     * @return
     */
    @GetMapping(value = "/checkProductStatusByCommandBillId")
    public boolean checkProductStatusByCommandBillId(@RequestParam(name = "commandBillId", required = true) String commandBillId) {
        if (mesCommandbillPitemService.checkProductStatusByCommandBillId(commandBillId)) {
            MesCommandbillInfo mesCommandbillInfo = mesCommandbillInfoService.getById(commandBillId);
            if (mesCommandbillInfo != null && StringUtils.isNotBlank(mesCommandbillInfo.getProduceId())) {
                MesOrderProduce mesOrderProduce = new MesOrderProduce();
                mesOrderProduce.setId(mesCommandbillInfo.getProduceId());//生产订单
                mesOrderProduce.setState("发料完成");
                return transactionClient.updatemesOrderProduce(mesOrderProduce);
            }
        }
        return false;
    }

    /**
     * 远程调用 根据生产订单ID查询制令单信息
     */
    @GetMapping(value = "/queryMesCommandBillInfoByProduceId")
    public List<MesCommandbillInfo> queryMesCommandBillInfoByProduceId(@RequestParam(name = "produceIds") List<String> produceIds) {
        return mesCommandbillInfoService.queryMesCommandBillInfoByProduceId(produceIds);
    }

    /**
     * 远程调用 根据制令单code查询制令单信息
     */
    @GetMapping(value = "/queryCommandBillInfoCode")
    public List<MesCommandbillInfo> queryCommandBillInfoCode(@RequestParam(name = "code") String code) {
        QueryWrapper<MesCommandbillInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("commandbill_code", code);
        return mesCommandbillInfoService.list(queryWrapper);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param mesCommandbillInfo
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, MesCommandbillInfo mesCommandbillInfo) {
        return super.exportXls(request, mesCommandbillInfo, MesCommandbillInfo.class, "制造中心-制令单信息");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, MesCommandbillInfo.class);
    }

    /*---------------------------------主表处理-end-------------------------------------*/

    /*--------------------------------子表处理-制令单BOM项目-begin----------------------------------------------*/

    /**
     * 通过主表ID查询
     *
     * @return
     */
    @AutoLog(value = "制令单BOM项目-通过主表ID查询")
    @ApiOperation(value = "制令单BOM项目-通过主表ID查询", notes = "制令单BOM项目-通过主表ID查询")
    @GetMapping(value = "/listMesCommandbillPitemByMainId")
    public Result<?> listMesCommandbillPitemByMainId(MesCommandbillPitem mesCommandbillPitem,
                                                     @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                     @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                     HttpServletRequest req) {
        QueryWrapper<MesCommandbillPitem> queryWrapper = QueryGenerator.initQueryWrapper(mesCommandbillPitem, req.getParameterMap());
        Page<MesCommandbillPitem> page = new Page<MesCommandbillPitem>(pageNo, pageSize);
        IPage<MesCommandbillPitem> pageList = mesCommandbillPitemService.page(page, queryWrapper);
        return Result.ok(pageList);
    }

    /**
     * 添加
     *
     * @param mesCommandbillPitem
     * @return
     */
    @AutoLog(value = "制令单BOM项目-添加")
    @ApiOperation(value = "制令单BOM项目-添加", notes = "制令单BOM项目-添加")
    @PostMapping(value = "/addMesCommandbillPitem")
    public Result<?> addMesCommandbillPitem(@RequestBody MesCommandbillPitem mesCommandbillPitem) {
        mesCommandbillPitemService.save(mesCommandbillPitem);
        return Result.ok("添加成功！");
    }

    /**
     * 编辑
     *
     * @param mesCommandbillPitem
     * @return
     */
    @AutoLog(value = "制令单BOM项目-编辑")
    @ApiOperation(value = "制令单BOM项目-编辑", notes = "制令单BOM项目-编辑")
    @PutMapping(value = "/editMesCommandbillPitem")
    public Result<?> editMesCommandbillPitem(@RequestBody MesCommandbillPitem mesCommandbillPitem) {
        mesCommandbillPitemService.updateById(mesCommandbillPitem);
        return Result.ok("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "制令单BOM项目-通过id删除")
    @ApiOperation(value = "制令单BOM项目-通过id删除", notes = "制令单BOM项目-通过id删除")
    @DeleteMapping(value = "/deleteMesCommandbillPitem")
    public Result<?> deleteMesCommandbillPitem(@RequestParam(name = "id", required = true) String id) {
        mesCommandbillPitemService.removeById(id);
        return Result.ok("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "制令单BOM项目-批量删除")
    @ApiOperation(value = "制令单BOM项目-批量删除", notes = "制令单BOM项目-批量删除")
    @DeleteMapping(value = "/deleteBatchMesCommandbillPitem")
    public Result<?> deleteBatchMesCommandbillPitem(@RequestParam(name = "ids", required = true) String ids) {
        this.mesCommandbillPitemService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.ok("批量删除成功!");
    }

    /**
     * 导出
     *
     * @return
     */
    @RequestMapping(value = "/exportMesCommandbillPitem")
    public ModelAndView exportMesCommandbillPitem(HttpServletRequest request, MesCommandbillPitem mesCommandbillPitem) {
        // Step.1 组装查询条件
        QueryWrapper<MesCommandbillPitem> queryWrapper = QueryGenerator.initQueryWrapper(mesCommandbillPitem, request.getParameterMap());
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        // Step.2 获取导出数据
        List<MesCommandbillPitem> pageList = mesCommandbillPitemService.list(queryWrapper);
        List<MesCommandbillPitem> exportList = null;

        // 过滤选中数据
        String selections = request.getParameter("selections");
        if (oConvertUtils.isNotEmpty(selections)) {
            List<String> selectionList = Arrays.asList(selections.split(","));
            exportList = pageList.stream().filter(item -> selectionList.contains(item.getId())).collect(Collectors.toList());
        } else {
            exportList = pageList;
        }

        // Step.3 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        mv.addObject(NormalExcelConstants.FILE_NAME, "制令单BOM项目"); //此处设置的filename无效 ,前端会重更新设置一下
        mv.addObject(NormalExcelConstants.CLASS, MesCommandbillPitem.class);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("制令单BOM项目报表", "导出人:" + sysUser.getRealname(), "制令单BOM项目"));
        mv.addObject(NormalExcelConstants.DATA_LIST, exportList);
        return mv;
    }

    /**
     * 导入
     *
     * @return
     */
    @RequestMapping(value = "/importMesCommandbillPitem/{mainId}")
    public Result<?> importMesCommandbillPitem(HttpServletRequest request, HttpServletResponse response, @PathVariable("mainId") String mainId) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取上传文件对象
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<MesCommandbillPitem> list = ExcelImportUtil.importExcel(file.getInputStream(), MesCommandbillPitem.class, params);
                for (MesCommandbillPitem temp : list) {
                    temp.setCommandbillId(mainId);
                }
                long start = System.currentTimeMillis();
                mesCommandbillPitemService.saveBatch(list);
                log.info("消耗时间" + (System.currentTimeMillis() - start) + "毫秒");
                return Result.ok("文件导入成功！数据行数：" + list.size());
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                return Result.error("文件导入失败:" + e.getMessage());
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.error("文件导入失败！");
    }

    /*--------------------------------子表处理-制令单BOM项目-end----------------------------------------------*/

}
